package karileet.meeting.profile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import karileet.meeting.profile.adapter.ComplexModelAdapter;
import karileet.meeting.profile.adapter.MergeAdapter;
import karileet.meeting.profile.adapter.RowModelAdapter;
import karileet.meeting.profile.model.ComplexModel;
import karileet.meeting.profile.model.RowModel;
import karileet.meeting.profile.model.ui.ComplexModelHolder;
import karileet.meeting.profile.model.ui.NotificationDialogFragment;
import karileet.meeting.profile.model.ui.RowModelHolder;
import karileet.meeting.profile.model.ui.ScheduleDialogFragment;

import android.net.Uri;
import android.os.Bundle;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.res.Resources;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RemoteViews;

/**
 * Main activity class for interactions done inside app
 * 
 * @author markus karileet
 */
public class MainActivity extends FragmentActivity {
	public static final String PREFS_NAME = "MeetingProfilePrefsFile";
	public static String APP = "Meeting profile";
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ArrayListFragment list = new ArrayListFragment();
	    if (savedInstanceState != null) {
	        getSupportFragmentManager().findFragmentByTag("thelist");
	    } else {
	        getSupportFragmentManager().beginTransaction().add(android.R.id.content, list, "thelist").commit(); 
	    }
		
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    }
    
    public static class ArrayListFragment extends ListFragment {
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
    		ArrayAdapter<RowModel> adapter = new RowModelAdapter(getActivity(), getToggleList());
    		ArrayAdapter<ComplexModel> adapter2 = new ComplexModelAdapter(getActivity(), getComplexList());
    		MergeAdapter ma = new MergeAdapter();
    		ma.addAdapter(adapter);
    		ma.addAdapter(adapter2);
    		setListAdapter(ma);
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
        	if (position > 3) {
        		this.handleComplexModel(v, position);
        	} else {
        		this.handleRowModel(v, position);
        	}
        }
    	private List<RowModel> getToggleList() {
    		Resources res = getResources();
    		String[] titles = res.getStringArray(R.array.listTitlesDefault);
    		String[] titlesAlt = res.getStringArray(R.array.listTitlesActive);
    		String[] descr = res.getStringArray(R.array.listDescriptionsDefault);
    		String[] descrAlt = res.getStringArray(R.array.listDescriptionsActive);
    		ProfileState ps = new ProfileState(getActivity());
    		List<RowModel> list = new ArrayList<RowModel>();
    	    list.add(new RowModel(titles[0], descr[0], titlesAlt[0], descrAlt[0], ps.isProfileEnabled()));
    	    list.add(new RowModel(titles[1], descr[1], titlesAlt[1], descrAlt[1], ps.isVibrateEnabled()));
    	    list.add(new RowModel(titles[2], descr[2], titlesAlt[2], descrAlt[2], true));
    	    list.add(new RowModel(titles[3], descr[3], titlesAlt[3], descrAlt[3], true));
    	    return list;
    	}
    	private List<ComplexModel> getComplexList() 
    	{
    		ProfileState ps = new ProfileState(getActivity());
  		    Date start = new Date(ps.getScheduleStart());
  		    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
  		    Date stop = new Date(ps.getScheduleStop());
    		List<ComplexModel> list = new ArrayList<ComplexModel>();
    		list.add(new ComplexModel("Enable", "Schedule enabling", sdf.format(start), ps.isScheduleStartEnabled(), 0));
    		list.add(new ComplexModel("Disable", "Schedule disabling", sdf.format(stop), ps.isScheduleStopEnabled(), 1));
    		return list;
    	}
    	
    	private void handleComplexModel(View v, int position) 
    	{
    		ComplexModelHolder cmh = (ComplexModelHolder) v.getTag();
    		ComplexModel model = cmh.getTag(); 
			
			cmh.setTitleText(model.getTitle());
			cmh.setDescriptionText(model.getDescription());
			ProfileState state = new ProfileState(getActivity());
			
    		
    		switch (position) {
	    		case 4:
	    			//schedule start
	    			state.setScheduleStartEnabled(model.isSelected());
					ScheduleDialogFragment sdf = new ScheduleDialogFragment();
					sdf.init("start", state);
					FragmentManager fm2 = getFragmentManager();
					sdf.show(fm2, "Schedule");
					break;
				case 5:
					//schedule stop
	    			state.setScheduleStopEnabled(model.isSelected());
					cmh.check(state.isScheduleStopEnabled());
					ScheduleDialogFragment sdf2 = new ScheduleDialogFragment();
					sdf2.init("stop", state);
					FragmentManager fm3 = getFragmentManager();
					sdf2.show(fm3, "Schedule");
				default:
					break;
    		}
    	}
    	private void handleRowModel(View v, int position)
    	{
    		RowModelHolder rmh = (RowModelHolder) v.getTag();
			RowModel model = rmh.getTag(); 
			model.toggle();
			rmh.setTitleText(model.getTitle());
			rmh.setDescriptionText(model.getDescription());
			MeetingProfile mp = new MeetingProfile(getActivity());
			ProfileState state = new ProfileState(getActivity());
			RemoteViews views = new RemoteViews(getActivity().getPackageName(),
					R.layout.meetingprofilewidget);
			switch (position) {
				case 0:
					if (model.isSelected()) {
						Log.d(MainActivity.APP, "Enabling profile");
						mp.enable(state);
						views.setImageViewResource(R.id.button1, R.drawable.mpbtn3_down);
					} else {
						Log.d(MainActivity.APP, "Disabling profile");
						mp.disable(state);	
						views.setImageViewResource(R.id.button1, R.drawable.mpbtn3_up);
					}
					AppWidgetManager manager = AppWidgetManager.getInstance(getActivity());
					manager.updateAppWidget(manager.getAppWidgetIds(new ComponentName(getActivity(), MeetingProfileWidgetProvider.class)), views);
					break;
				case 1:
					state.setVibrateEnabled(model.isSelected());
					mp.update(state);
					break;
				case 2:
					NotificationDialogFragment ndf = new NotificationDialogFragment();
					FragmentManager fm = getFragmentManager();
					ndf.show(fm, "Popup");
					break;
				case 3:
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, 
						Uri.parse("https://play.google.com/store/apps/details?id=karileet.meeting.profile")
					);
					startActivity(browserIntent);
					break;	
				default:
					break;
			}
    	}
    }
}
